import json
from datetime import datetime
from pathlib import Path

TEMPLATES_FILE_PATH = "data/templates.json"
MY_ECARDS_FILE_PATH = "data/my_ecards.json"


def load_templates():
    """加载模板（从文件或硬编码）"""
    try:
        with open(TEMPLATES_FILE_PATH, "r", encoding="utf-8") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        print("模板文件加载失败，使用硬编码模板...")
        from template_manager import get_hardcoded_templates  # 避免循环导入，按需加载
        return get_hardcoded_templates()


def load_my_ecards():
    """加载已保存的贺卡（探索功能）"""
    try:
        with open(MY_ECARDS_FILE_PATH, "r", encoding="utf-8") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        print("未找到已保存的贺卡或文件损坏。")
        return []


def save_my_ecard(ecard_data_to_save):
    """保存贺卡到JSON文件（探索功能）"""
    # 生成唯一ID和时间戳
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    ecard_id = f"ecard_{timestamp}"
    saved_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 构造完整数据
    full_ecard_data = {
        "ecard_id": ecard_id,
        "saved_at": saved_at,
        **ecard_data_to_save  # 合并基础数据
    }

    # 读取现有数据并写入
    my_ecards = load_my_ecards()
    my_ecards.append(full_ecard_data)

    try:
        with open(MY_ECARDS_FILE_PATH, "w", encoding="utf-8") as f:
            json.dump(my_ecards, f, indent=4, ensure_ascii=False)
        print(f"贺卡已保存（ID：{ecard_id}）！")
    except Exception as e:
        print(f"保存失败：{str(e)}")


def view_my_saved_ecards_interaction(my_ecards_list):
    """查看已保存贺卡的交互（探索功能）"""
    if not my_ecards_list:
        print("暂无已保存的贺卡！")
        return

    # 展示摘要列表
    print("\n===== 已保存的贺卡 =====")
    for idx, ecard in enumerate(my_ecards_list, 1):
        print(f"{idx}. ID: {ecard['ecard_id']} | 模板: {ecard['template_name_used']} | 保存时间: {ecard['saved_at']}")

    # 选择查看具体贺卡
    choice = input("请输入要查看的贺卡序号（或按回车返回）：").strip()
    if choice.isdigit():
        idx = int(choice) - 1
        if 0 <= idx < len(my_ecards_list):
            selected_ecard = my_ecards_list[idx]
            print("\n===== 贺卡内容 ======")
            print(selected_ecard['generated_text'])
            print("=======================")
        else:
            print("无效序号！")